package cn.tedu.boot51.controller;

import cn.tedu.boot51.entity.User;
import cn.tedu.boot51.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper mapper;
    @RequestMapping("/reg")
    public int reg(@RequestBody User user)
    {
        if(mapper.selectByUsername(user.getUsername())!=null){

           return 2;
        }
         mapper.insert(user);
         return 1;
    }
    @RequestMapping("/login")
    //在参数列表里面声明session,既可以得到当前客户端所对应的Session
    public int  login(@RequestBody User user,HttpSession session){
        User u = mapper.selectByUsername(user.getUsername() );
        if(u !=null){
            if(u.getPassword().equals(user.getPassword())){
                //这里的u代表用户的所有信息,user这里是只有用户输入的账号密码
                //把当前登录的用户对象保存到会话对象中
                session.setAttribute("user",u);
                return 1;
            }
            return 3;
        }
        return 2;
    }
    @RequestMapping("/currentUser")
    public User currentUser(HttpSession session)
    {   //从会话对象中得到登录成功时保存的用户对象
        User u = (User)session.getAttribute("user");
        return u;
    }
    @RequestMapping("/logout")
    public void logout(HttpSession session){
        //把登录成功时保存的user对象删除
        session.removeAttribute("user");
    }
}
